import request from "@/utils/request";
import { message } from "ant-design-vue";

const baseApiUrl = import.meta.env.VITE_APP_BASE_API;

enum Api {
  loadDictItem = "/sys/category/loadDictItem/",
  getDictItems = "/sys/dict/getDictItems/",
}

/**
 * 上传父路径
 */
export const uploadUrl = `${baseApiUrl}/common/upload`;

/**
 * 根据字典code加载字典text
 */
export const loadDictItem = (params?) => {
  return request.get(Api.loadDictItem + params);
};

/**
 * 根据字典code加载字典text
 */
export const getDictItems = (dictCode) => {
  return request.get(Api.getDictItems + dictCode);
};

/**
 * 文件上传
 */
export const uploadFile = (params) => {
  return request.post("/common/upload", params, {
    headers: {
      "Content-type": "multipart/form-data;charset=UTF-8"
    }
  });
};


/**
 * 下载文件 用于excel导出
 * @param url
 * @param parameter
 * @returns {*}
 */
export const getFileblob = (url) => {
  return request.get(
    url,
    {
      responseType: "blob"
    }
  );
};

/**
 * 下载文件
 * @param url 文件路径
 * @param fileName 文件名
 * @param parameter
 * @returns {*}
 */
export const downloadFile = (url, fileName?) => {
  return getFileblob(url).then((data: any) => {
    if (!data || data.size === 0) {
      message.warning("文件下载失败");
      return;
    }
    if (typeof window.navigator.msSaveBlob !== "undefined") {
      window.navigator.msSaveBlob(new Blob([data]), fileName);
    } else {
      let url = window.URL.createObjectURL(new Blob([data]));
      let link = document.createElement("a");
      link.style.display = "none";
      link.href = url;
      link.setAttribute("download", fileName);
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link); //下载完成移除元素
      window.URL.revokeObjectURL(url); //释放掉blob对象
    }
  });
};
